<template>
    <div>
        <n-spin :show="loading">
            <div class="box-border py-5 flex items-center justify-between">
                <div>设置角色对应的功能操作、后台管理权限</div>
                <NButton @click="insertRoleRoute" size="small" type="primary">添加</NButton>
            </div>
            <div class="px-6 box-border overflow-auto">
                <TreeOption v-if="visible && identity" :key="identity" v-model:select="select" />
            </div>
        </n-spin>
    </div>
</template>

<script setup lang="ts">
import {Api} from '@/api/type'
import {onMounted, ref} from 'vue'
import {RoleApi} from '@/api/role'
import {NButton, useMessage} from 'naive-ui'
import TreeOption from '@/view/system/route/tree-option/index.vue'

type RoleRelateRoute = Api.System.RoleRelateRoute

const loading = ref(false)
const message = useMessage()
const roleApi = new RoleApi()
const visible = ref<boolean>(false)
const relateList = ref<RoleRelateRoute[]>([])
const select = ref<Map<string, boolean>>(new Map<string, boolean>())

const {identity} = defineProps({
    identity: {
        type: String,
        default: ''
    }
})

async function getSelectList() {
    if (!identity) {
        relateList.value = []
    } else {
        visible.value = false
        let result = await roleApi.getRoleRelateRoute(identity)
        relateList.value = result.data || []
        relateList.value.forEach(item => {
            select.value.set(item.identity, !!item.roleRouteId)
        })
        visible.value = true
    }
}

async function insertRoleRoute() {
    try {
        loading.value = true

        let routeId: Array<string> = []
        select.value.forEach((value, key) => {
            if (value) {
                routeId.push(key)
            }
        })
        let result = await roleApi.addRoleRelateRoute(identity, routeId)
        if (result.code == 0) {
            message.success('操作成功')
        } else {
            message.error(result.message || '操作失败, 请稍后再试')
        }
    } catch (error) {

    } finally {
        loading.value = false
    }
}

async function initialize() {
    await getSelectList()
}

onMounted(() => {
    initialize()
})
</script>
